package com.op.parcel.manage.config.security;

import com.op.parcel.common.constant.CommonConstant;
import com.op.parcel.manage.modules.sys.entity.Permission;
import com.op.parcel.manage.modules.sys.entity.Role;
import com.op.parcel.manage.modules.sys.vo.UserVO;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author xuan🐽
 */
@Slf4j
public class MyUserDetails extends UserVO implements UserDetails {

	private static final long serialVersionUID = 1L;

	MyUserDetails(UserVO user) {
		if (user != null) {
			this.setId(user.getId());
			this.setUsername(user.getUsername());
			this.setPassword(user.getPassword());
			this.setStatus(user.getStatus());
			this.setRoles(user.getRoles());
			this.setPermissions(user.getPermissions());
		}
	}

	/**
	 * 添加用户拥有的权限和角色
	 *
	 * @return
	 */
	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		List<GrantedAuthority> authorityList = new ArrayList<>();
		List<Permission> permissions = this.getPermissions();
		// 添加请求权限
		if (permissions != null && permissions.size() > 0) {
			for (Permission permission : permissions) {
				if (CommonConstant.PERMISSION_INTERFACE.equals(permission.getType())
					&& StringUtils.isNotBlank(permission.getTitle())
					&& StringUtils.isNotBlank(permission.getPath())) {
					authorityList.add(new SimpleGrantedAuthority(permission.getTitle()));
				}
			}
		}
		// 添加角色
		List<Role> roles = this.getRoles();
		if (roles != null && roles.size() > 0) {
			roles.forEach(item -> {
				if (StringUtils.isNotBlank(item.getName())) {
					authorityList.add(new SimpleGrantedAuthority(item.getName()));
				}
			});
		}
		return authorityList;
	}

	/**
	 * 账户是否过期
	 *
	 * @return
	 */
	@Override
	public boolean isAccountNonExpired() {
		return true;
	}

	/**
	 * 是否禁用
	 *
	 * @return
	 */
	@Override
	public boolean isAccountNonLocked() {
		return !CommonConstant.STATUS_LOCK.equals(this.getDelFlag());
	}

	/**
	 * 密码是否过期
	 *
	 * @return
	 */
	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	/**
	 * 是否启用
	 *
	 * @return
	 */
	@Override
	public boolean isEnabled() {
		return CommonConstant.STATUS_NORMAL.equals(this.getStatus());
	}
}
